package cn.wolfcode.luowowo.mgrsite.listener;


import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.cache.key.RedisKey;
import cn.wolfcode.luowowo.cache.service.IStrategyStatsCacheService;
import cn.wolfcode.luowowo.cache.vo.StrategyStats;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;
@Component
public class HotDataListener implements ApplicationListener<ContextRefreshedEvent>{
    @Value("${hotData.init}")
    private Boolean hotData;
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private IStrategyStatsCacheService statsCacheService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if(hotData){
            //从mysql获取数据
            List<StrategyDetail> details =  strategyDetailService.selectAll();
            //遍历,设置对应属性进StrategyStats
            for (StrategyDetail detail : details) {
                //先判断redis中不存在stats才执行下面的
                if (!statsCacheService.isExistStats(detail.getId())) {
                    StrategyStats stats = new StrategyStats();
                    stats.setStrategyId(detail.getId());
                    stats.setDestId(detail.getDest().getId());
                    stats.setDestName(detail.getDest().getName());
                    stats.setTitle(detail.getTitle());
                    stats.setFavornum(detail.getFavornum());
                    stats.setReplynum(detail.getReplynum());
                    stats.setSharenum(detail.getSharenum());
                    stats.setViewnum(detail.getViewnum());
                    stats.setThumbsupnum(detail.getThumbsupnum());
                    //调用cache的方法,存进缓存中
                    statsCacheService.setStatsCache(stats);
                }
                //zset不存在对应的key-name的时候,初始化两个榜单
                //这里说的name是zset的value,只是因为存储的时候还有一个相关String,所以这里习惯叫name
                if(!statsCacheService.isExistRank(RedisKey.STRATEGY_STATS_UP_SORT, detail.getId())){
                    statsCacheService.addRank(RedisKey.STRATEGY_STATS_UP_SORT,
                            detail.getId(), detail.getViewnum()+detail.getReplynum());
                }
                if(!statsCacheService.isExistRank(RedisKey.STRATEGY_STATS_HOT_SORT, detail.getId())){
                    statsCacheService.addRank(RedisKey.STRATEGY_STATS_HOT_SORT,
                            detail.getId(), detail.getFavornum()+detail.getThumbsupnum());
                }
            }
        }
    }
}
